package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
//因为这个类是进行订单超时处理和结算派送完成的订单的；
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron="0 * * * * ?")  //这个cron表达式表示每1分钟执行一次
    public void processTimeOutOrder(){
        log.info("从此刻开始处理超时订单，{}", LocalDateTime.now());
        //先查下有没有超时订单（where当前时间-15min,且status是编号1的待支付）
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);//表示超过15分钟就超时
        List<Orders> ordersList = orderMapper.getByOrderTimeAndStatus(Orders.PENDING_PAYMENT, time);
        //如果有，就设置订单状态为6
        if(ordersList!=null && !ordersList.isEmpty()){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时，支付取消");
                orders.setCancelTime(LocalDateTime.now());
                //一定记住最后一定要落地到数据库更改中去
                orderMapper.update(orders);
            });    //lambda表达式
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("从此刻开始处理未完成订单，{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);//表示超过15分钟就超时
        List<Orders> ordersList = orderMapper.getByOrderTimeAndStatus(Orders.DELIVERY_IN_PROGRESS, time);
        if(ordersList!=null && !ordersList.isEmpty()){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                //一定记住最后一定要落地到数据库更改中去
                orderMapper.update(orders);
            });    //lambda表达式
        }
    }

}
